package utils;


import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    public static String createToken(String phone){
        //token包含三部分值
        //头部信息，
        Map<String,Object> headMap=new HashMap<>();
        headMap.put("alg","HS256");
        headMap.put("type","JWT");
        //有效载荷
        Map<String,Object> payLoad=new HashMap<>();
        payLoad.put("phone",phone);
        payLoad.put("data",new Date());

        //失效时间
        long startTime=System.currentTimeMillis();
        long endTime=startTime+600000000;
        //签名
        String token= Jwts.builder()
                .setHeader(headMap)
                .setClaims(payLoad)
                .setExpiration(new Date(endTime))
                .signWith(SignatureAlgorithm.HS256,"zhangsan")
                .compact();
        return token;
    }

    /**
     * 解析token方法
     * @param token
     * @return
     */
    public static ResultObj getClaimsFromToken(String token){
        try {
            Jwts.parser()
                    .setSigningKey("zhangsan")
                    .parseClaimsJws(token)
                    .getBody();
            return  ResultObj.success();
        }
        catch (Exception e){
            return  ResultObj.error();
        }

    }
    public static String getPhoneFromToken(String token){
        try {
            Claims zhangsan = Jwts.parser()
                    .setSigningKey("zhangsan")
                    .parseClaimsJws(token)
                    .getBody();
            String username = (String) zhangsan.get("phone");
            return username;
        } catch (Exception e) {
            return  null;
        }


    }
}
